package com.xci.platform.auth.service;

import com.github.pagehelper.Page;
import com.xci.platform.annotation.OperateUser;
import com.xci.platform.annotation.QueryMap;
import com.xci.platform.auth.core.AuthConstant;
import com.xci.platform.auth.dao.MessageDao;
import com.xci.platform.auth.dao.UserDao;
import com.xci.platform.auth.entity.MessageEntity;
import com.xci.platform.auth.entity.UserEntity;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.core.GMap;
import com.xci.platform.core.Simple;
import com.xci.platform.helper.CoreHelper;
import com.xci.platform.helper.MapHelper;
import com.xci.platform.helper.StringHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统消息服务
 */
@Service
public class MessageService extends AuthBaseService {

    /**
     * 系统消息数据访问对象
     */
    @Resource
    private MessageDao messageDao;

    /**
     * 系统用户数据访问对象
     */
    @Resource
    private UserDao userDao;

    /**
     * 保存系统消息
     *
     * @param entity 系统消息对象
     */
    @Validated
    @OperateUser
    @Transactional(rollbackFor = Exception.class)
    public BoolMessage save(MessageEntity entity) {
        long startTime = CoreHelper.startWatch();
        messageDao.insert(entity);
        // 操作日志
        String msg = StringHelper.format("新增系统消息 {}", entity.getTitle());
        operateLog(AuthConstant.SystemModule.Message, msg, CoreHelper.stopWatch(startTime));
        return BoolMessage.True;
    }

    /**
     * 发送系统消息
     */
    @Validated
    @Transactional(rollbackFor = Exception.class)
    public BoolMessage send(String title, String messageContent, String sendUserId, String receiveUserId) {
        long startTime = CoreHelper.startWatch();
        MessageEntity entity = new MessageEntity();
        UserEntity user = userDao.queryById(sendUserId);
        entity.setSendUserId(user.getId());
        entity.setSendUserName(user.getName());
        entity.setTitle(title);
        entity.setMessageContent(messageContent);
        entity.setReadStatus(0);
        entity.setReadDatetime(null);

        List<Simple> userSimpleList;
        if (receiveUserId.equals("-1")) {
            userSimpleList = userDao.querySimple(null);
        } else {
            String[] userIdList = StringHelper.splitToArray(receiveUserId);
            userSimpleList = userDao.querySimple(GMap.newMap("userIds", userIdList));
        }
        for (Simple simple : userSimpleList) {
            entity.setId(StringHelper.guid());
            entity.setSendDateTime(new Date());
            entity.setReceiveUserId(simple.getId());
            entity.setReceiveUserName(simple.getName());
            messageDao.insert(entity);
        }

        // 操作日志
        String msg = StringHelper.format("新增系统消息 共{}条", userSimpleList.size());
        operateLog(AuthConstant.SystemModule.Message, msg, CoreHelper.stopWatch(startTime));
        return BoolMessage.True;
    }

    /**
     * 更新读取状态
     *
     * @param id 主键
     */
    public BoolMessage updateReadStatus(String id) {
        long startTime = CoreHelper.startWatch();
        messageDao.updateReadStatus(id, new Date());

        // 操作日志
        String msg = StringHelper.format("读取系统消息,消息id:{}", id);
        operateLog(AuthConstant.SystemModule.Message, msg, CoreHelper.stopWatch(startTime));
        return BoolMessage.True;
    }

    /**
     * 删除系统消息
     *
     * @param id 系统消息主键数组
     */
    @Validated
    @Transactional(rollbackFor = Exception.class)
    public BoolMessage delete(@NotEmpty(message = "请指定删除的系统消息主键") String id) {
        long startTime = CoreHelper.startWatch();
        messageDao.delete(id);

        // 操作日志
        String msg = "删除系统消息";
        operateLog(AuthConstant.SystemModule.Message, msg, CoreHelper.stopWatch(startTime));
        return BoolMessage.True;
    }

    /**
     * 获取指定接收人的未读消息
     * @param userId 请指定接收人主键
     */
    public Integer queryUnReadCountByUserId(@NotNull(message = "请指定接收人主键")String userId){
        return messageDao.queryUnReadCountByUserId(userId);
    }

    /**
     * 根据系统消息主键获取系统消息对象
     *
     * @param id 系统消息主键
     * @return 返回指定系统消息主键的系统消息对象
     */
    @Validated
    public MessageEntity queryById(@NotNull(message = "请指定系统消息主键") String id) {
        return messageDao.queryById(id);
    }

    /**
     * 查询系统消息分页列表
     *
     * @param params 查询系统消息
     * @return 返回符合查询条件的系统消息分页列表
     */
    @QueryMap
    public Page<MessageEntity> queryPage(Map params) {
        MapHelper.setQueryDateTimeParam(params);
        return (Page<MessageEntity>) messageDao.query(params);
    }
}
